(async function () {
  const vis = require("vis");

  async function loadItems(
    timeline,
    timelineItemsDataSet,
    timelineGroupsDataSet
  ) {
    const todoNotes = await api.runAsyncOnBackendWithManualTransactionHandling(async () => {
      const todoNotes = (
        await api.searchForNotes(
          "(#todoItem and #dueDate) and (note.ancestors.labels.todoBacklog or note.ancestors.labels.todoInProgress or note.ancestors.labels.todoDone)"
        )
      ).map((m) => ({
        noteId: m.noteId,
        title: m.title,
        dueDate: m.getLabelValue("dueDate"),
        project: m.getLabelValue("project"),
        isTracking: m.hasLabel("startedAt"),
      }));

      return todoNotes;
    });

    timelineItemsDataSet.clear();

    todoNotes.forEach((m, i) => {
      let item = {
        id: ++i,
        content: m.title,
        start: m.dueDate,
        type: "box",
        limitSize: true,
        group: m.project || "",
        noteId: m.noteId,
        isTracking: m.isTracking,
      };

      if (m.isTracking) {
        item.className = "tracking";
      }

      timelineItemsDataSet.add(item);
    });

    timeline.setItems(timelineItemsDataSet);

    timeline.fit();
  }

  async function getSelectedNotesIds(timeline) {
      const selectedNote = timeline.getSelection()[0];
      if (selectedNote) {
         //api.showMessage(timeline.getSelection().map((m) => timeline.itemsData.get(m).noteId));
        return timeline.getSelection().map((m) => timeline.itemsData.get(m).noteId);
      }else{
            api.showMessage("请选择笔记。");
      }
      
    
  }

  var options = {
    locale: "en",
    align: "left",
    min: dayjs().subtract(3, "day").format("YYYY-MM-DD"),
    max: dayjs().add(7, "day").format("YYYY-MM-DD"),
    height: "100%",
    zoomMax: 950400000,
    zoomMin: 345600000,
    margin: {
      item: 15,
    },
    showCurrentTime: true,
    selectable: true,
    multiselect: true,
    editable: {
      add: false,
      updateTime: false,
      updateGroup: false,
      remove: false,
    },
  };

  const $timeline = $("#todo-timeline");

  const $timelineMenu = $("#todo-timeline-menu");

  const timelineItemsDataSet = new vis.DataSet();

  const timelineGroupsDataSet = new vis.DataSet();

  var timeline = new vis.Timeline(
    $timeline.get(0),
    timelineItemsDataSet,
    null,
    options
  );

  timeline.on("doubleClick", async (properties) => {
    if (properties.what === "item") {
      const selectedNote = timeline.getSelection()[0];
      if (selectedNote) {
        await api.activateNote(timeline.itemsData.get(selectedNote).noteId);
      }
    }
  });

  timeline.on("select", async (properties) => {
      const selectedNote = timeline.getSelection()[0];
      if (selectedNote) {
         //api.showMessage(timeline.getSelection().map((m) => timeline.itemsData.get(m).noteId));
         $timelineMenu.show(); 
          /**
        if(timeline.itemsData.get(selectedNote).isTracking){
            //properties.items?.length ? $timelineMenu.show() : $timelineMenu.hide();
        }else{
           // $timelineMenu.hide();
        }*/
      }else{
          $timelineMenu.hide();
      }
      
    
  });

  $timelineMenu.find("#todoUnschedule").click(async () => {
    await api.runAsyncOnBackendWithManualTransactionHandling(
      async (notesIds) => {
        api.transactional( async () => {
            await timelineUnschedule(notesIds);
        });
      },
      [timeline.getSelection().map((m) => timeline.itemsData.get(m).noteId)]
    );

    await api.waitUntilSynced();

    await loadItems(timeline, timelineItemsDataSet, timelineGroupsDataSet);
  });

  $timelineMenu.find("#todoComplete").click(async () => {
    await api.runAsyncOnBackendWithManualTransactionHandling(
      async (notesIds) => {
        api.transactional( async () => {
            await timelineComplete(notesIds);
        });
      },
      [timeline.getSelection().map((m) => timeline.itemsData.get(m).noteId)]
    );

    await api.waitUntilSynced();

    await loadItems(timeline, timelineItemsDataSet, timelineGroupsDataSet);
  });

  $timelineMenu.find("#todoStopTracking").click(async () => {   
    await api.runAsyncOnBackendWithManualTransactionHandling(
      async (taskNoteId) => {
        api.transactional( async () => {
            await timelineStopTracking(taskNoteId);
        });
      },
      [timeline.getSelection().map((m) => timeline.itemsData.get(m).noteId)]
    );
      
    await api.waitUntilSynced();
      
    await loadItems(timeline, timelineItemsDataSet, timelineGroupsDataSet);
  });

  $timelineMenu.find("#todoStartTracking").click(async () => {
    await api.runAsyncOnBackendWithManualTransactionHandling(
      async (notesIds) => {
        api.transactional( async () => {
            await timelineStartTracking(notesIds);
        });
      },
      [timeline.getSelection().map((m) => timeline.itemsData.get(m).noteId)]
    );
    
    await api.waitUntilSynced();

    await loadItems(timeline, timelineItemsDataSet, timelineGroupsDataSet);
  });

  await loadItems(timeline, timelineItemsDataSet, timelineGroupsDataSet);
})();
